<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas绘制多边形</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
</head>
<body>
<style>
    canvas {
        border: 1px solid #333;
        display: block;
    }

    input {
        width: 100px;
        margin-left: 200px;
        margin-top: 650px;
    }

    #canvas{
        position: absolute;
        left: 0;
        top: 0;
        z-index: 1;
        cursor: crosshair;
    }

    #canvasSave{
        position: absolute;
        left: 0;
        top: 0;
    }
</style>
<!--用来和鼠标进行交互操作的canvas-->
<canvas id="canvas" width="1280px" height="720px"></canvas>
<!--存储已生成的点线，避免被清空-->
<canvas id="canvasSave" width="1280px" height="720px"></canvas>
<input id="deleteCanvas" type="button" value="清空选区">

<script>
    var can = document.getElementById("canvas");
    var ctx = can.getContext('2d');
    var canSave = document.getElementById("canvasSave");
    var ctxSave = canSave.getContext('2d');

    var pointX, pointY;
    var pointArr = [];//存放坐标的数组

    ctx.strokeStyle = 'rgba(102,168,255,1)';//线条颜色
    ctx.lineWidth = 4;//线条粗细
    ctxSave.strokeStyle = 'rgba(102,168,255,1)';//线条颜色
    ctxSave.lineWidth = 4;//线条粗细

    var oIndex = -1;//判断鼠标是否移动到起始点处，-1为否，1为是

    /*点击画点*/
    $(can).click(function (e) {
        if (e.offsetX || e.layerX) {
            pointX = e.offsetX == undefined ? e.layerX : e.offsetX;
            pointY = e.offsetY == undefined ? e.layerY : e.offsetY;
            var piX,piY;
            if(oIndex > 0 && pointArr.length > 0){
                piX = pointArr[0].x;
                piY = pointArr[0].y;
                //画点
                makearc(ctx, piX, piY, GetRandomNum(2, 2), 0, 180, 'rgba(102,168,255,1)');
                pointArr.push({x: piX, y: piY});
                canvasSave(pointArr);//保存点线同步到另一个canvas
                saveCanvas();//生成画布
            }else {
                piX = pointX;
                piY = pointY;
                makearc(ctx, piX, piY, GetRandomNum(2, 2), 0, 180, 'rgba(102,168,255,1)');
                pointArr.push({x: piX, y: piY});
                canvasSave(pointArr);//保存点线同步到另一个canvas
            }
        }
    });

    /*  */
    $(can).mousemove(function (e) {
        if (e.offsetX || e.layerX) {
            pointX = e.offsetX == undefined ? e.layerX : e.offsetX;
            pointY = e.offsetY == undefined ? e.layerY : e.offsetY;
            var piX,piY;
            /*清空画布*/
            ctx.clearRect(0, 0, can.width, can.height);
            /*鼠标下跟随的圆点*/
            makearc(ctx, pointX, pointY, GetRandomNum(4, 4), 0, 180, 'rgba(102,168,255,1)');

            if (pointArr.length > 0) {
                if((pointX > pointArr[0].x-15 && pointX < pointArr[0].x+15) && (pointY > pointArr[0].y-15 && pointY < pointArr[0].y+15)){
                    if(pointArr.length>1){
                        piX = pointArr[0].x;
                        piY = pointArr[0].y;
                        ctx.clearRect(0, 0, can.width, can.height);
                        makearc(ctx, piX, piY, GetRandomNum(4, 4), 0, 180, 'rgba(102,168,255,1)');
                        oIndex = 1;
                    }
                }else {
                    piX = pointX;
                    piY = pointY;
                    oIndex = -1;
                }
                /*开始绘制*/
                ctx.beginPath();
                ctx.moveTo (pointArr[0].x, pointArr[0].y);
                if (pointArr.length > 1){
                    for (var i = 1; i < pointArr.length; i++){
                        ctx.lineTo(pointArr[i].x, pointArr[i].y);
                    }
                }
                ctx.lineTo(piX, piY);
                ctx.fillStyle = 'rgba(161,195,255,1)';//填充颜色
                ctx.fill();//填充
                ctx.stroke();//绘制
            }
        }
    });

    // 存储已生成的点线
    function canvasSave(pointArr){
        ctxSave.clearRect(0, 0, ctxSave.width, ctxSave.height);
        ctxSave.beginPath();
        if (pointArr.length > 1){
            ctxSave.moveTo (pointArr[0].x, pointArr[0].y);
            for (var i = 1; i < pointArr.length; i++){
                ctxSave.lineTo(pointArr[i].x, pointArr[i].y);
                ctxSave.fillStyle = 'rgba(161,195,255,1)';//填充颜色
                //ctxSave.fill();
                ctxSave.stroke();//绘制
            }
            ctxSave.closePath();
        }
    }

    /*生成画布 结束绘画*/
    function saveCanvas() {
        ctx.clearRect(0, 0, can.width, can.height);
        ctxSave.closePath();//结束路径状态，结束当前路径，如果是一个未封闭的图形，会自动将首尾相连封闭起来
        ctxSave.fill();//填充
        ctxSave.stroke();//绘制

        console.log("sssssssss",this.pointArr,this.pointArr.length)

        this.pointArr.pop();
        var pointArr1 = [];
        var pointArr1_Length;
        this.pointArr1 = this.pointArr
        pointArr1_Length = this.pointArr1.length
        console.log("aaaaaaa",this.pointArr1)
        console.log("bbbbbb",pointArr1_Length)

        // 在发送请求前打印data
    var data = {
        pointArr1: this.pointArr1,
        pointArr1_Length: pointArr1_Length
    };
    console.log("Sending data:", data);


    loadData(data);
        pointArr = [];
        pointArr1 = [];
    }

// 发送-----------------------------------------
function loadData(data) {
    // 创建 XMLHttpRequest 对象
    var xhr = new XMLHttpRequest();

    // 配置请求类型、URL 和是否异步执行
    

    // 设置请求头，告诉服务器我们将发送JSON格式的数据
    // xhr.setRequestHeader("Content-Type", "application/json");

    // // 设置请求完成后的回调函数
    // xhr.onload = function() {
    //     if (xhr.status === 200) { // 请求成功
    //         // 处理返回的数据
    //         document.getElementById("result").innerHTML = JSON.stringify(xhr.response, null, 2);
    //     } else {
    //         // 错误处理
    //         console.error('An error occurred:', xhr.statusText);
    //     }
    // };

    // 设置错误处理函数
    xhr.onerror = function() {
        console.error('A network error occurred.');
    };

    let send_json=JSON.stringify(data)
    
    console.log("Sending data:", send_json);
    xhr.open("get", "test_sat?json="+send_json, true);
    // 发送请求
    // xhr.send();
}
//-----------------------------------------------------------------------

    /*清空选区*/
    $('#deleteCanvas').click(function () {
        ctx.clearRect(0, 0, can.width, can.height);
        ctxSave.clearRect(0, 0, canSave.width, canSave.height);
        pointArr = [];
    });

    /*验证canvas画布是否为空函数*/
    function isCanvasBlank(canvas) {
        var blank = document.createElement('canvas');//创建一个空canvas对象
        blank.width = canvas.width;
        blank.height = canvas.height;
        return canvas.toDataURL() == blank.toDataURL();//为空 返回true
    }

    /*canvas生成圆点*/
    function GetRandomNum(Min, Max) {
        var Range = Max - Min;
        var Rand = Math.random();
        return (Min + Math.round(Rand * Range));
    }
    function makearc(ctx, x, y, r, s, e, color) {
        ctx.clearRect(0, 0, 199, 202);//清空画布
        ctx.beginPath();
        ctx.fillStyle = color;
        ctx.arc(x, y, r, s, e);
        ctx.fill();
    }


</script>
</body>
</html>

